import { PureComponent } from "react"

export default class DeepAssign extends PureComponent {
  constructor() {
    super()
    this.state = {
      bookList: [
        { price: 99, name: "书名1" },
        { price: 88, name: "书名2" }
      ]
    }
  }
  addItem() {
    console.log("addItem 执行")
    /** 1. 直接修改原有数据对象，在PureComponent中是不会触发render函数的 */
    // this.state.bookList.push({name: '书名3', price: 100});
    // this.setState({
    //     bookList: this.state.bookList,
    // })
    /** 2.这样可以，直接创建新的地址。*/
    const bookList = [...this.state.bookList]
    bookList.push({ name: "书名" + (bookList.length + 1), price: 100 })
    this.setState({ bookList })
  }

  addPrice(index) {
    console.log("addPrice 执行")
    /** 虽然内部只是Object.is浅层对比，更改的也是同一个对象{name:xx,price:xx}的地址
         但过这样是可以触发render的，react这样设计也是可以闭环的, 如果直接传item进来 页面是不会重新render的 */
    const bookList = [...this.state.bookList]
    bookList[index]["price"]++
    this.setState({ bookList })
  }

  render() {
    const { bookList } = this.state
    return (
      <div>
        <button onClick={() => this.addItem()}>新增一本书</button>
        {bookList.map((book, index) => {
          return (
            <div key={index}>
              <span>{book.name}</span>
              <span style={{ padding: "10px", color: "red" }}>
                {book.price}
              </span>
              <button onClick={() => this.addPrice(index)}>价格加1</button>
            </div>
          )
        })}
      </div>
    )
  }
}
